<template>
  <el-cascader
    v-model="model"
    v-loading="isLoading"
    :options="shops"
    :props="cascaderProps"
    @change="handleChange"
  />
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import { CascaderNodePathValue, CascaderProps, CascaderValue } from "element-plus";
import { ShopResponse } from "@/api/types/shop";
import { getShops } from "@/api/shop";

const props = defineProps<{ type: "shopId" | "shopIds" }>();
const model = defineModel<CascaderValue>();
const shops = ref<ShopResponse[]>([]);
const shopId = defineModel<number>("shopId");
const flacktype = defineModel<any>("flacktype");
const shopIds = defineModel<number[]>("shopIds");
  const is_leave = defineModel<any>("is_leave");

const isLoading = ref(false);
const cascaderProps: CascaderProps = {
  // checkStrictly: true,
  children: "childs",
  label: "shop_name",
  value: "selfid",
};

watch(flacktype, (aa, bb) => {
  model.value = undefined;
});

watch(is_leave, (aa, bb) => {
  model.value = undefined;
});

async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true;
  }
  const { result } = await getShops();
  if (result !== undefined) {
    shops.value = result;
    isLoading.value = false;
  }
}

getData();

function handleChange(values: CascaderValue) {  
  if (Array.isArray(values)) {
    if (props.type === "shopId") {
      shopId.value = values[(values.length - 1)] as number;      
    } else if (props.type === "shopIds" && values.every((values) => Array.isArray(values))) {
      shopIds.value = (values as CascaderNodePathValue[]).map((arr) =>
        Number(arr[arr.length - 1])
      );
      console.log(shopId.value);
    }
  }
}
</script>
